using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media;

namespace WPF_MVVM_Test.MVVM_View.UserControl
{
    public partial class AiChat : System.Windows.Controls.UserControl
    {
        public AiChat()
        {
            InitializeComponent();
            
            // 订阅 DataContext 变更事件
            this.DataContextChanged += AiChat_DataContextChanged;
            
            // 订阅加载完成事件
            this.Loaded += AiChat_Loaded;
        }

        private void AiChat_Loaded(object sender, RoutedEventArgs e)
        {
            // 确保绑定到消息集合变更事件
            if (DataContext is MVVM_ViewModel.ChatViewModel viewModel)
            {
                if (viewModel.ChatMessages is INotifyCollectionChanged notifyCollection)
                {
                    notifyCollection.CollectionChanged -= ChatMessages_CollectionChanged;
                    notifyCollection.CollectionChanged += ChatMessages_CollectionChanged;
                }
                
                // 强制刷新一次
                if (ChatItemsControl != null)
                {
                    ChatItemsControl.Items.Refresh();
                }
                ScrollToBottom();
            }
        }

        private void AiChat_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            // 取消旧的数据上下文的订阅
            if (e.OldValue is MVVM_ViewModel.ChatViewModel oldViewModel)
            {
                if (oldViewModel.ChatMessages is INotifyCollectionChanged oldCollection)
                {
                    oldCollection.CollectionChanged -= ChatMessages_CollectionChanged;
                }
                
                if (oldViewModel is INotifyPropertyChanged oldNotify)
                {
                    oldNotify.PropertyChanged -= ViewModel_PropertyChanged;
                }
            }
            
            // 订阅新的数据上下文
            if (e.NewValue is MVVM_ViewModel.ChatViewModel newViewModel)
            {
                if (newViewModel.ChatMessages is INotifyCollectionChanged newCollection)
                {
                    newCollection.CollectionChanged += ChatMessages_CollectionChanged;
                }
                
                if (newViewModel is INotifyPropertyChanged newNotify)
                {
                    newNotify.PropertyChanged += ViewModel_PropertyChanged;
                }
                
                // 强制刷新一次
                if (ChatItemsControl != null)
                {
                    ChatItemsControl.Items.Refresh();
                }
            }
        }
        
        private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // 当 ChatMessages 属性变更时，刷新列表并滚动到底部
            if (e.PropertyName == nameof(MVVM_ViewModel.ChatViewModel.ChatMessages))
            {
                Dispatcher.InvokeAsync(() => {
                    if (ChatItemsControl != null)
                    {
                        ChatItemsControl.Items.Refresh();
                        System.Diagnostics.Debug.WriteLine("强制刷新ItemsControl");
                    }
                    ScrollToBottom();
                });
            }
        }

        private void ChatMessages_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            // 当集合变更时，刷新列表并滚动到底部
            Dispatcher.InvokeAsync(() => {
                if (ChatItemsControl != null)
                {
                    ChatItemsControl.Items.Refresh();
                }
                ScrollToBottom();
            });
        }
        
        private void ScrollToBottom()
        {
            // 确保在UI线程上执行
            Dispatcher.InvokeAsync(() =>
            {
                try
                {
                    if (ChatScrollViewer != null)
                    {
                        System.Diagnostics.Debug.WriteLine("滚动到底部");
                        ChatScrollViewer.ScrollToEnd();
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine("ChatScrollViewer为null，无法滚动");
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine($"滚动异常: {ex.Message}");
                }
            });
        }

        private void MessageTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && !Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
            {
                e.Handled = true;
                
                if (DataContext is MVVM_ViewModel.ChatViewModel viewModel && viewModel.SendMessageCommand.CanExecute(null))
                {
                    viewModel.SendMessageCommand.Execute(null);
                    
                    // 强制刷新一次
                    if (ChatItemsControl != null)
                    {
                        ChatItemsControl.Items.Refresh();
                    }
                }
            }
        }
    }

    public class BoolToAlignmentConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool isUser)
            {
                return isUser ? HorizontalAlignment.Right : HorizontalAlignment.Left;
            }
            return HorizontalAlignment.Left;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    
    public class BoolToBackgroundConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool isUser)
            {
                return isUser ? new SolidColorBrush(Color.FromRgb(230, 248, 230)) : new SolidColorBrush(Colors.White);
            }
            return new SolidColorBrush(Colors.White);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    
    public class BoolToForegroundConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool isUser)
            {
                return isUser ? new SolidColorBrush(Color.FromRgb(0, 100, 0)) : new SolidColorBrush(Color.FromRgb(51, 51, 51));
            }
            return new SolidColorBrush(Color.FromRgb(51, 51, 51));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}